clear all;
close all;

%  =======================================================================================================================================================
%
%  Code Description:
%  This codefile constructs the dataset underlying figures 6 (Active trading during the COVID 19-induced stress period) and 
%  IA.7 (Flow-driven and discretionary trading during the COVID 19-induced market stress period).
%
%  =======================================================================================================================================================
%
%  Major output:
%  - dataset underlying figures 6 and IA.7
%  =======================================================================================================================================================
%
%  General disclaimer:
%  This file directory produces replication code for "Connected Funds".
%  Because we cannot share the underlying data provided by the Bundesbank's Research Data and Service Centre (RDSC) and other subscription data sources,
%  we have included pseudo data to show how the raw data are formatted. 
%  Other researchers can go through a similar approval and subscription process to obtain the underlying data. (2023-04-06)
%
%  =======================================================================================================================================================


%% Set project directory

projectPath = 'C:\ConnectedFunds_Codebase\'

% Add functions folders
addpath(strcat(projectPath, 'Code\matlab_functions'));


%  ======================================================================== Preparations ==========================================================================


% Load fund data
load(strcat(projectPath, 'Data\IFS_All_CleanData'));

% Filter fund data
IFS_All(IFS_All.artmittel == 4, :) = [];
IFS_All(IFS_All.artmittel == 6, :) = [];
IFS_All(IFS_All.artmittel > 7, :) = [];
IFS_All(IFS_All.etf == 1, :) = [];

% Set-up result variables - aggregate results across all funds
All_Results                 = [];
All_Results_PriceEffect     = [];
All_Results_NoPriceEffect   = [];

All_ResultsPerc                 = [];
All_ResultsPerc_PriceEffect     = [];
All_ResultsPerc_NoPriceEffect   = [];

All_TotalHoldings       = [];
All_TotalHoldings_Lag   = [];

All_TotalFlows  = [];
All_Outflows    = [];

% Set-up result variables - aggregate results across institutional funds
All_Spezial_Results                 = [];
All_Spezial_Results_PriceEffect     = [];
All_Spezial_Results_NoPriceEffect   = [];

All_Spezial_ResultsPerc                 = [];
All_Spezial_ResultsPerc_PriceEffect     = [];
All_Spezial_ResultsPerc_NoPriceEffect   = [];

All_Spezial_TotalHoldings       = [];
All_Spezial_TotalHoldings_Lag   = [];

All_Spezial_TotalFlows      = [];
All_Spezial_TotalCash       = [];
All_Spezial_TotalLeverage   = [];
All_Spezial_TotalAktiva     = [];
All_Spezial_TotalPassiva    = [];
All_Spezial_TotalFondsverm  = [];

All_Spezial_Results_FlowDriven      = [];
All_Spezial_Results_Discretionary   = [];


%  ======================== Loop over time and build dataset on funds' trading activity during the Covid-episode (differentiate between corp. bonds, sov. bonds, equities, fund shares) ==========================


for t = 2 : length(umonth)

    umonth(t),

    % Get funds' holdings in (t-1) 
    load(strcat(projectPath, 'Data\IFS\mat\IFS_Holdings_',num2str(umonth(t-1)),'.mat'));
    IFS_Holdings_1     = IFS_Holdings;
    IFS_Holdings_1(IFS_Holdings_1.AMOUNT<0,:) = [];
    IFS_Holdings_1.SECPRICE(startsWith(IFS_Holdings_1.SECQUOT,"P")) = IFS_Holdings_1.SECPRICE(startsWith(IFS_Holdings_1.SECQUOT,"P"))./100;

    % Get funds' holdings in t 
    load(strcat(projectPath, 'Data\IFS\mat\IFS_Holdings_',num2str(umonth(t)),'.mat'));
    IFS_Holdings_2     = IFS_Holdings;
    IFS_Holdings_2(IFS_Holdings_2.AMOUNT<0,:) = [];
    IFS_Holdings_2.SECPRICE(startsWith(IFS_Holdings_2.SECQUOT,"P")) = IFS_Holdings_2.SECPRICE(startsWith(IFS_Holdings_2.SECQUOT,"P"))./100;

    clear IFS_Holdings;

    % Keep funds that report in both months
    ufund  = intersect(IFS_Holdings_1.ISIN, IFS_Holdings_2.ISIN);
    [~,idx] = ismember(IFS_Holdings_1.ISIN,ufund); IFS_Holdings_1(idx==0,:) = [];
    [~,idx] = ismember(IFS_Holdings_2.ISIN,ufund); IFS_Holdings_2(idx==0,:) = [];

    % Keep assets that were reported in both months;
    uasset = intersect(IFS_Holdings_1.SECCODE, IFS_Holdings_2.SECCODE);
    [~,idx] = ismember(IFS_Holdings_1.SECCODE,uasset); IFS_Holdings_1(idx==0,:) = [];
    [~,idx] = ismember(IFS_Holdings_2.SECCODE,uasset); IFS_Holdings_2(idx==0,:) = [];
    clear idx

    ufund  = intersect(IFS_Holdings_1.ISIN, IFS_Holdings_2.ISIN);
    [~,idx] = ismember(IFS_Holdings_1.ISIN,ufund); IFS_Holdings_1(idx==0,:) = [];
    [~,idx] = ismember(IFS_Holdings_2.ISIN,ufund); IFS_Holdings_2(idx==0,:) = [];

    uasset = intersect(IFS_Holdings_1.SECCODE, IFS_Holdings_2.SECCODE); 
    ufund  = intersect(IFS_Holdings_1.ISIN, IFS_Holdings_2.ISIN);

    % Merge security-level data from CSDB 
    load(strcat(projectPath, 'Data\CSDB\mat\CSDB_',num2str(umonth(t)),'.mat'));
    CSDB_2 = sortrows(CSDB,'ISIN','ascend');
    clear CSDB

    [~,idx]             = ismember(CSDB_2.ISIN,uasset);
    CSDB_2(idx==0,:)    = [];
    [~,idx]             = ismember(uasset,CSDB_2.ISIN);
    uasset(idx==0)      = [];
    clear idx;

    load(strcat(projectPath, 'Data\CSDB\mat\CSDB_',num2str(umonth(t-1)),'.mat'));
    CSDB_1 = sortrows(CSDB,'ISIN','ascend');
    clear CSDB;

    CSDB_2.PRICE_Lag            = NaN(height(CSDB_2),1);
    [~,idx]                     = ismember(CSDB_2.ISIN,CSDB_1.ISIN);
    CSDB_2.PRICE_Lag(idx>0,:)   = CSDB_1.PRICE(idx(idx>0));

    CSDB_2.Return                           = (CSDB_2.PRICE - CSDB_2.PRICE_Lag)./CSDB_2.PRICE_Lag;
    CSDB_2.Return(abs(CSDB_2.Return)==Inf)  = NaN;
    ql                                      = quantile(CSDB_2.Return,0.01);
    qh                                      = quantile(CSDB_2.Return,1-0.01);
    CSDB_2.Return(CSDB_2.Return > qh)       = qh;
    CSDB_2.Return(CSDB_2.Return < ql)       = ql;
    clear CSDB_1;

    % Condition on large outflows for additional analysis
    ifs_t   = IFS_All(IFS_All.DATUM == umonth(t),:);
    ifs_lag = IFS_All(IFS_All.DATUM == umonth(t-1),:);

    [~,idx]         = ismember(ufund,ifs_t.ISIN);
    Flows           = NaN(length(ufund),1);
    Flows(idx>0)    = ifs_t.Netflows(idx(idx>0));

    k_outflows = find(Flows<-0.01);

    All_TotalFlows(t) = nansum(ifs_t.MITTELZUFL - ifs_t.MITTELABFL);
    All_Outflows(t)   = nansum(ifs_t.MITTELZUFL(ifs_t.Netflows<-0.01) - ifs_t.MITTELABFL(ifs_t.Netflows<-0.01));

    Spezial         = NaN(length(ufund),1);
    Spezial(idx>0)  = ifs_t.SPEZIAL(idx(idx>0));
    k_spezial       = find(Spezial == 1);

    All_Spezial_TotalFlows(t,1) = nansum(ifs_t.MITTELZUFL(ifs_t.SPEZIAL == 1) - ifs_t.MITTELABFL(ifs_t.SPEZIAL == 1));
    All_Spezial_TotalFlows(t,2) = nansum(ifs_t.MITTELZUFL(ifs_t.SPEZIAL == 0) - ifs_t.MITTELABFL(ifs_t.SPEZIAL == 0));

    All_Spezial_TotalCash(t,1) = nansum(ifs_t.BANKG(ifs_t.SPEZIAL == 1));
    All_Spezial_TotalCash(t,2) = nansum(ifs_t.BANKG(ifs_t.SPEZIAL == 0));

    All_Spezial_TotalLeverage(t,1) = nansum(ifs_t.bilanzsumme(ifs_t.SPEZIAL == 1))/nansum(ifs_t.FONDSVERM(ifs_t.SPEZIAL == 1));
    All_Spezial_TotalLeverage(t,2) = nansum(ifs_t.bilanzsumme(ifs_t.SPEZIAL == 0))/nansum(ifs_t.FONDSVERM(ifs_t.SPEZIAL == 0));

    All_Spezial_TotalAktiva(t,1) = nansum(ifs_t.AKTIVA(ifs_t.SPEZIAL == 1));
    All_Spezial_TotalAktiva(t,2) = nansum(ifs_t.AKTIVA(ifs_t.SPEZIAL == 0));

    All_Spezial_TotalPassiva(t,1) = nansum(ifs_t.PASSIVA(ifs_t.SPEZIAL == 1));
    All_Spezial_TotalPassiva(t,2) = nansum(ifs_t.PASSIVA(ifs_t.SPEZIAL == 0));

    All_Spezial_TotalFondsverm(t,1) = nansum(ifs_t.FONDSVERM(ifs_t.SPEZIAL == 1));
    All_Spezial_TotalFondsverm(t,2) = nansum(ifs_t.FONDSVERM(ifs_t.SPEZIAL == 0));

    ifs_match = outerjoin(ifs_t,ifs_lag,'keys','ISIN','type','left');
    ifs_match(isnan(ifs_match.DATUM_ifs_lag),:) = [];

    F = ifs_match.MITTELZUFL_ifs_t - ifs_match.MITTELABFL_ifs_t;
    delta_cash = ifs_match.BANKG_ifs_t - ifs_match.BANKG_ifs_lag;
    i = find(isnan(F+delta_cash));
    F(i) = NaN; delta_cash(i) = NaN;

    % Employ flow-driven vs. discretionary trading framework as provided by Shek et al.
    [flow_driven, discretionary] = ShekEtAl(F,delta_cash);

    All_Spezial_Results_FlowDriven(t,1) = nansum(flow_driven(ifs_match.SPEZIAL_ifs_t == 1));
    All_Spezial_Results_FlowDriven(t,2) = nansum(flow_driven(ifs_match.SPEZIAL_ifs_t == 0));

    All_Spezial_Results_Discretionary(t,1) = nansum(discretionary(ifs_match.SPEZIAL_ifs_t == 1));
    All_Spezial_Results_Discretionary(t,2) = nansum(discretionary(ifs_match.SPEZIAL_ifs_t == 0));

    % Do some housekeeping
    clear ifs_* i F delta_cash idx Flows flow_driven discretionary;

    [~,idxAsset_1] = ismember(IFS_Holdings_1.SECCODE,uasset);
    IFS_Holdings_1(idxAsset_1 == 0,:) = []; idxAsset_1(idxAsset_1==0) = [];
    [~,idxAsset_2] = ismember(IFS_Holdings_2.SECCODE,uasset);
    IFS_Holdings_2(idxAsset_2 == 0,:) = []; idxAsset_2(idxAsset_2==0) = [];

    [~,idxFund_1]  = ismember(IFS_Holdings_1.ISIN,ufund);
    [~,idxFund_2]  = ismember(IFS_Holdings_2.ISIN,ufund);

    % Aggregate asset-level prices and holdings
    AssetPrice_1       = accumarray([idxFund_1 idxAsset_1],IFS_Holdings_1.SECPRICE,[length(ufund) length(uasset)],'', 0);
    TotalHoldingsNum_1 = accumarray([idxFund_1 idxAsset_1],IFS_Holdings_1.SECNOMUN,[length(ufund) length(uasset)],'', 0);

    AssetPrice_2       = accumarray([idxFund_2 idxAsset_2],IFS_Holdings_2.SECPRICE,[length(ufund) length(uasset)],'', 0);
    TotalHoldingsNum_2 = accumarray([idxFund_2 idxAsset_2],IFS_Holdings_2.SECNOMUN,[length(ufund) length(uasset)],'', 0);

    % Compute funds' total holdings
    TotalHoldings_1          = nansum((TotalHoldingsNum_1 .* AssetPrice_1))';
    TotalHoldings_2          = nansum((TotalHoldingsNum_2 .* AssetPrice_2))';
    TotalHoldings_2_PriceLag = TotalHoldings_2./(1 + CSDB_2.Return);

    % Outflows
    Outflows_TotalHoldings_1          = nansum((TotalHoldingsNum_1(k_outflows,:) .* AssetPrice_1(k_outflows,:)))';
    Outflows_TotalHoldings_2          = nansum((TotalHoldingsNum_2(k_outflows,:) .* AssetPrice_2(k_outflows,:)))';
    Outflows_TotalHoldings_2_PriceLag = Outflows_TotalHoldings_2./(1 + CSDB_2.Return);

    % Compute institutional funds's total holdings
    Spezial_TotalHoldings_1          = nansum((TotalHoldingsNum_1(k_spezial,:) .* AssetPrice_1(k_spezial,:)))';
    Spezial_TotalHoldings_2          = nansum((TotalHoldingsNum_2(k_spezial,:) .* AssetPrice_2(k_spezial,:)))';
    Spezial_TotalHoldings_2_PriceLag = Spezial_TotalHoldings_2./(1 + CSDB_2.Return);

    clear IFS_Holdings* idx* k_* 

    % Classify assets into bonds (1), equities (2) and fund shares (3)
    AssetType = 1*startsWith(CSDB_2.ESA_INS_1995,'F.3') + ...
        2*startsWith(CSDB_2.ESA_INS_1995,'F.51') + ...
        3*startsWith(CSDB_2.ESA_INS_1995,'F.52');
    AssetSov  = startsWith(CSDB_2.ESA_ISSUER_1995,'S.13');
    [~,idx] = ismember(uasset,ufund);
    AssetGerman = startsWith(uasset,'DE') + startsWith(CSDB_2.ISSUER_COUNTRY,'DE') + (idx>0);
    AssetGerman = (AssetGerman>0);

    AssetFundType = NaN(length(AssetGerman),1);
    AssetUCITS    = NaN(length(AssetGerman),1);
    AssetNonUCITS    = NaN(length(AssetGerman),1);    

    if umonth(t) <= 201912
        load(strcat(projectPath, 'Data\ECB_IF_List\mat\IF_',num2str(floor(umonth(t)/100)),'_Q4.mat'));
    else
        load(strcat(projectPath, 'Data\ECB_IF_List\mat\IF_',num2str(2019),'_Q4.mat'));
    end
    
    % Classify fund shares into shares of bond funds, equity funds and mixed securities funds
    IF_Data.FundType = (startsWith(IF_Data.InvestmentPolicy,'equities') + startsWith(IF_Data.InvestmentPolicy,'Equities')) + ...
        2*(startsWith(IF_Data.InvestmentPolicy,'bonds') + startsWith(IF_Data.InvestmentPolicy,'Bonds')) + ...
        3*(startsWith(IF_Data.InvestmentPolicy,'mixed') + startsWith(IF_Data.InvestmentPolicy,'Mixed')); % + ...
    IF_Data.FundType(IF_Data.FundType == 0) = 4; 
    IF_Data.UCITS    = startsWith(IF_Data.UCITSCompliance,'UCITS') + startsWith(IF_Data.UCITSCompliance,'ucits');
    IF_Data.NonUCITS = startsWith(IF_Data.UCITSCompliance,'Non') + startsWith(IF_Data.UCITSCompliance,'non');
    
    if umonth(t) < 201701
        IF_Data.DE       = startsWith(IF_Data.HostCountry,'DE');
    else
        IF_Data.DE       = startsWith(IF_Data.CountryOfResidence,'DE');
    end

    [~,idx]                 = ismember(uasset,IF_Data.ISIN);
    AssetFundType(idx>0)    = IF_Data.FundType(idx(idx>0));
    AssetType(idx>0)        = 3;
    AssetUCITS(idx>0)       = IF_Data.UCITS(idx(idx>0));
    AssetNonUCITS(idx>0)    = IF_Data.NonUCITS(idx(idx>0));
    AssetGerman(idx>0)      = double(AssetGerman(idx>0) + IF_Data.DE(idx(idx>0)) >0);
    clear idx IF_Data;
    

    %  ======================== Calculate holdings changes for all funds ==========================
    

    DeltaHoldings                  = (TotalHoldings_2 - TotalHoldings_1);
    DeltaHoldings_NoPriceEffect    = TotalHoldings_2_PriceLag - TotalHoldings_1;
    DeltaHoldings_PriceEffect      = TotalHoldings_2 - TotalHoldings_2_PriceLag;

    [nansum(DeltaHoldings) nansum(TotalHoldings_2)-nansum(TotalHoldings_1) nansum(DeltaHoldings_NoPriceEffect)];

    All_TotalHoldings(t,:) = 10^-9*[nansum(TotalHoldings_2) ...
        nansum(TotalHoldings_2(AssetType == 1 & AssetSov == 0)) ...
        nansum(TotalHoldings_2(AssetType == 1 & AssetSov == 1)) ...
        nansum(TotalHoldings_2(AssetType == 2)) ...
        nansum(TotalHoldings_2(AssetType == 3)) ...
        nansum(TotalHoldings_2(AssetType == 3 & AssetGerman == 1))];

    All_TotalHoldings_Lag(t,:) = 10^-9*[nansum(TotalHoldings_1) ...
        nansum(TotalHoldings_1(AssetType == 1 & AssetSov == 0)) ...
        nansum(TotalHoldings_1(AssetType == 1 & AssetSov == 1)) ...
        nansum(TotalHoldings_1(AssetType == 2)) ...
        nansum(TotalHoldings_1(AssetType == 3)) ...
        nansum(TotalHoldings_1(AssetType == 3 & AssetGerman == 1))];

    % Compute holdings changes including price effects
    TotalChange         = 10^-9*nansum(TotalHoldings_2 - TotalHoldings_1);

    CorpBondChange      = 10^-9*nansum(TotalHoldings_2(AssetType == 1 & AssetSov == 0 ) - TotalHoldings_1(AssetType == 1 & AssetSov == 0));
    SovBondChange       = 10^-9*nansum(TotalHoldings_2(AssetType == 1 & AssetSov == 1) - TotalHoldings_1(AssetType == 1 & AssetSov == 1));
    EquityChange        = 10^-9*nansum(TotalHoldings_2(AssetType == 2) - TotalHoldings_1(AssetType == 2));
    FundChange          = 10^-9*nansum(TotalHoldings_2(AssetType == 3) - TotalHoldings_1(AssetType == 3));
    FundChangeDE        = 10^-9*nansum(TotalHoldings_2(AssetType == 3 & AssetGerman == 1) - TotalHoldings_1(AssetType == 3  & AssetGerman == 1));
    FundChange1         = 10^-9*nansum(TotalHoldings_2(AssetFundType == 1) - TotalHoldings_1(AssetFundType == 1));
    FundChange2         = 10^-9*nansum(TotalHoldings_2(AssetFundType == 2) - TotalHoldings_1(AssetFundType == 2));
    FundChange3         = 10^-9*nansum(TotalHoldings_2(AssetFundType == 3) - TotalHoldings_1(AssetFundType == 3));
    FundChange4         = 10^-9*nansum(TotalHoldings_2(AssetFundType == 4) - TotalHoldings_1(AssetFundType == 4));
    FundChangeUCITS     = 10^-9*nansum(TotalHoldings_2(AssetUCITS == 1) - TotalHoldings_1(AssetUCITS == 1));
    FundChangenonUCITS  = 10^-9*nansum(TotalHoldings_2(AssetNonUCITS == 1) - TotalHoldings_1(AssetNonUCITS == 1));

    FundChangeDE1           = 10^-9*nansum(TotalHoldings_2(AssetGerman == 1 & AssetFundType == 1) - TotalHoldings_1(AssetGerman == 1 & AssetFundType == 1));
    FundChangeDE2           = 10^-9*nansum(TotalHoldings_2(AssetGerman == 1 & AssetFundType == 2) - TotalHoldings_1(AssetGerman == 1 & AssetFundType == 2));
    FundChangeDE3           = 10^-9*nansum(TotalHoldings_2(AssetGerman == 1 & AssetFundType == 3) - TotalHoldings_1(AssetGerman == 1 & AssetFundType == 3));
    FundChangeDE4           = 10^-9*nansum(TotalHoldings_2(AssetGerman == 1 & AssetFundType == 4) - TotalHoldings_1(AssetGerman == 1 & AssetFundType == 4));
    FundChangeDEUCITS       = 10^-9*nansum(TotalHoldings_2(AssetGerman == 1 & AssetUCITS == 1)    - TotalHoldings_1(AssetGerman == 1 & AssetUCITS == 1));
    FundChangeDEnonUCITS    = 10^-9*nansum(TotalHoldings_2(AssetGerman == 1 & AssetNonUCITS == 1)    - TotalHoldings_1(AssetGerman == 1 & AssetNonUCITS == 1));

    Results = [TotalChange CorpBondChange SovBondChange EquityChange FundChange FundChangeDE FundChange1 FundChange2 FundChange3 FundChange4 FundChangeUCITS FundChangenonUCITS];

    % Compute holdings changes excluding price effects
    TotalChange_NoPriceEffect = 10^-9*nansum(DeltaHoldings_NoPriceEffect);

    CorpBondChange_NoPriceEffect       = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetType==1 & AssetSov == 0)); 
    SovBondChange_NoPriceEffect        = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetType==1 & AssetSov == 1)); 
    EquityChange_NoPriceEffect         = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetType==2)); 
    FundChange_NoPriceEffect           = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetType==3)); 
    FundChangeDE_NoPriceEffect         = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetType == 3 & AssetGerman == 1));
    FundChange1_NoPriceEffect          = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetFundType == 1));
    FundChange2_NoPriceEffect          = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetFundType == 2));
    FundChange3_NoPriceEffect          = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetFundType == 3));
    FundChange4_NoPriceEffect          = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetFundType == 4));
    FundChangeUCITS_NoPriceEffect      = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetUCITS == 1));
    FundChangenonUCITS_NoPriceEffect   = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetNonUCITS == 1));

    FundChangeDE1_NoPriceEffect        = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetGerman == 1 & AssetFundType == 1));
    FundChangeDE2_NoPriceEffect        = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetGerman == 1 & AssetFundType == 2));
    FundChangeDE3_NoPriceEffect        = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetGerman == 1 & AssetFundType == 3));
    FundChangeDE4_NoPriceEffect        = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetGerman == 1 & AssetFundType == 4));
    FundChangeDEUCITS_NoPriceEffect    = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetGerman == 1 & AssetUCITS == 1));
    FundChangeDEnonUCITS_NoPriceEffect = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetGerman == 1 & AssetNonUCITS == 1));

    Results_NoPriceEffect = [TotalChange_NoPriceEffect CorpBondChange_NoPriceEffect SovBondChange_NoPriceEffect EquityChange_NoPriceEffect FundChange_NoPriceEffect FundChangeDE_NoPriceEffect FundChange1_NoPriceEffect FundChange2_NoPriceEffect FundChange3_NoPriceEffect FundChange4_NoPriceEffect FundChangeUCITS_NoPriceEffect FundChangenonUCITS_NoPriceEffect];

    % Compute only price effects
    TotalChange_PriceEffect     = 10^-9*nansum(DeltaHoldings_PriceEffect);

    CorpBondChange_PriceEffect  = 10^-9*nansum(DeltaHoldings_PriceEffect(AssetType==1 & AssetSov == 0)); 
    SovBondChange_PriceEffect   = 10^-9*nansum(DeltaHoldings_PriceEffect(AssetType==1 & AssetSov == 1)); 
    EquityChange_PriceEffect    = 10^-9*nansum(DeltaHoldings_PriceEffect(AssetType==2)); 
    FundChange_PriceEffect      = 10^-9*nansum(DeltaHoldings_PriceEffect(AssetType==3)); 
    FundChangeDE_PriceEffect    = 10^-9*nansum(DeltaHoldings_PriceEffect(AssetType == 3 & AssetGerman == 1));

    Results_PriceEffect = [TotalChange_PriceEffect CorpBondChange_PriceEffect SovBondChange_PriceEffect EquityChange_PriceEffect FundChange_PriceEffect FundChangeDE_PriceEffect];

    % Save results for all funds
    All_Results = [All_Results; Results];
    All_Results_PriceEffect = [All_Results_PriceEffect; Results_PriceEffect];
    All_Results_NoPriceEffect = [All_Results_NoPriceEffect; Results_NoPriceEffect];

    All_ResultsPerc = [All_ResultsPerc; Results./All_TotalHoldings_Lag(t)];
    All_ResultsPerc_PriceEffect = [All_ResultsPerc_PriceEffect; Results_PriceEffect./All_TotalHoldings_Lag(t)];
    All_ResultsPerc_NoPriceEffect = [All_ResultsPerc_NoPriceEffect; Results_NoPriceEffect./All_TotalHoldings_Lag(t)];


    %  ======================== Calculate holdings changes for institutional funds ==========================


    TotalHoldings_2 = Spezial_TotalHoldings_2;
    TotalHoldings_1 = Spezial_TotalHoldings_1;
    TotalHoldings_2_PriceLag = Spezial_TotalHoldings_2_PriceLag;

    DeltaHoldings                  = (TotalHoldings_2 - TotalHoldings_1);
    DeltaHoldings_NoPriceEffect    = TotalHoldings_2_PriceLag - TotalHoldings_1;
    DeltaHoldings_PriceEffect      = TotalHoldings_2 - TotalHoldings_2_PriceLag;

    All_Spezial_TotalHoldings(t,:) = 10^-9*[nansum(TotalHoldings_2) ...
        nansum(TotalHoldings_2(AssetType == 1 & AssetSov == 0)) ...
        nansum(TotalHoldings_2(AssetType == 1 & AssetSov == 1)) ...
        nansum(TotalHoldings_2(AssetType == 2)) ...
        nansum(TotalHoldings_2(AssetType == 3)) ...
        nansum(TotalHoldings_2(AssetType == 3 & AssetGerman == 1))];

    All_Spezial_TotalHoldings_Lag(t,:) = 10^-9*[nansum(TotalHoldings_1) ...
        nansum(TotalHoldings_1(AssetType == 1 & AssetSov == 0)) ...
        nansum(TotalHoldings_1(AssetType == 1 & AssetSov == 1)) ...
        nansum(TotalHoldings_1(AssetType == 2)) ...
        nansum(TotalHoldings_1(AssetType == 3)) ...
        nansum(TotalHoldings_1(AssetType == 3 & AssetGerman == 1))];

    % Compute holdings changes including price effects
    TotalChange     = 10^-9*nansum(TotalHoldings_2 - TotalHoldings_1);

    CorpBondChange  = 10^-9*nansum(TotalHoldings_2(AssetType == 1 & AssetSov == 0 ) - TotalHoldings_1(AssetType == 1 & AssetSov == 0));
    SovBondChange   = 10^-9*nansum(TotalHoldings_2(AssetType == 1 & AssetSov == 1) - TotalHoldings_1(AssetType == 1 & AssetSov == 1));
    EquityChange    = 10^-9*nansum(TotalHoldings_2(AssetType == 2) - TotalHoldings_1(AssetType == 2));
    FundChange      = 10^-9*nansum(TotalHoldings_2(AssetType == 3) - TotalHoldings_1(AssetType == 3));
    FundChangeDE    = 10^-9*nansum(TotalHoldings_2(AssetType == 3 & AssetGerman == 1) - TotalHoldings_1(AssetType == 3  & AssetGerman == 1));
    FundChange1    = 10^-9*nansum(TotalHoldings_2(AssetFundType == 1) - TotalHoldings_1(AssetFundType == 1));
    FundChange2    = 10^-9*nansum(TotalHoldings_2(AssetFundType == 2) - TotalHoldings_1(AssetFundType == 2));
    FundChange3    = 10^-9*nansum(TotalHoldings_2(AssetFundType == 3) - TotalHoldings_1(AssetFundType == 3));
    FundChange4    = 10^-9*nansum(TotalHoldings_2(AssetFundType == 4) - TotalHoldings_1(AssetFundType == 4));
    FundChangeUCITS    = 10^-9*nansum(TotalHoldings_2(AssetUCITS == 1) - TotalHoldings_1(AssetUCITS == 1));

    Results = [TotalChange CorpBondChange SovBondChange EquityChange FundChange FundChangeDE FundChange1 FundChange2 FundChange3 FundChange4 FundChangeUCITS];

    % Compute holdings changes excluding price effects
    TotalChange_NoPriceEffect = 10^-9*nansum(DeltaHoldings_NoPriceEffect);

    CorpBondChange_NoPriceEffect  = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetType==1 & AssetSov == 0)); 
    SovBondChange_NoPriceEffect   = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetType==1 & AssetSov == 1)); 
    EquityChange_NoPriceEffect    = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetType==2)); 
    FundChange_NoPriceEffect      = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetType==3)); 
    FundChangeDE_NoPriceEffect   = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetType == 3 & AssetGerman == 1));
    FundChange1_NoPriceEffect   = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetFundType == 1));
    FundChange2_NoPriceEffect   = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetFundType == 2));
    FundChange3_NoPriceEffect   = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetFundType == 3));
    FundChange4_NoPriceEffect   = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetFundType == 4));
    FundChangeUCITS_NoPriceEffect   = 10^-9*nansum(DeltaHoldings_NoPriceEffect(AssetUCITS == 1));

    Results_NoPriceEffect = [TotalChange_NoPriceEffect CorpBondChange_NoPriceEffect SovBondChange_NoPriceEffect EquityChange_NoPriceEffect FundChange_NoPriceEffect FundChangeDE_NoPriceEffect FundChange1_NoPriceEffect FundChange2_NoPriceEffect FundChange3_NoPriceEffect FundChange4_NoPriceEffect FundChangeUCITS_NoPriceEffect];

    % Compute only price effects
    TotalChange_PriceEffect = 10^-9*nansum(DeltaHoldings_PriceEffect);

    CorpBondChange_PriceEffect  = 10^-9*nansum(DeltaHoldings_PriceEffect(AssetType==1 & AssetSov == 0)); 
    SovBondChange_PriceEffect   = 10^-9*nansum(DeltaHoldings_PriceEffect(AssetType==1 & AssetSov == 1)); 
    EquityChange_PriceEffect    = 10^-9*nansum(DeltaHoldings_PriceEffect(AssetType==2)); 
    FundChange_PriceEffect      = 10^-9*nansum(DeltaHoldings_PriceEffect(AssetType==3)); 
    FundChangeDE_PriceEffect   = 10^-9*nansum(DeltaHoldings_PriceEffect(AssetType == 3 & AssetGerman == 1));

    Results_PriceEffect = [TotalChange_PriceEffect CorpBondChange_PriceEffect SovBondChange_PriceEffect EquityChange_PriceEffect FundChange_PriceEffect FundChangeDE_PriceEffect];

    % Save results for instutional funds
    All_Spezial_Results                   = [All_Spezial_Results; Results];
    All_Spezial_Results_PriceEffect       = [All_Spezial_Results_PriceEffect; Results_PriceEffect];
    All_Spezial_Results_NoPriceEffect     = [All_Spezial_Results_NoPriceEffect; Results_NoPriceEffect];

    All_Spezial_ResultsPerc               = [All_Spezial_ResultsPerc; Results./All_Spezial_TotalHoldings_Lag(t)];
    All_Spezial_ResultsPerc_PriceEffect   = [All_Spezial_ResultsPerc_PriceEffect; Results_PriceEffect./All_Spezial_TotalHoldings_Lag(t)];
    All_Spezial_ResultsPerc_NoPriceEffect = [All_Spezial_ResultsPerc_NoPriceEffect; Results_NoPriceEffect./All_Spezial_TotalHoldings_Lag(t)];

    % Do some housekeeping
    clear idx* Asset* Bond* Corp* CSDB* date DE* Delta* Equity* Fund* qh ql Results* Sov* Total* uasset ufund Outflows* Spezial*;

end

% Again, do some housekeeping
clear IFS_All IFS* t ans Tmonth;


%  ======================================================================================== Save dataset ================================================================================================


% As we look into differences, kill first rows which contain no values
umonth(1)           = []; 
dates               = datenum(num2str(umonth),'yyyymm');

All_TotalFlows(1)           = [];
All_TotalHoldings(1,:)      = [];
All_TotalHoldings_Lag(1,:)  = [];
All_Outflows(1)             = [];

All_Spezial_Results_FlowDriven(1,:)     = [];
All_Spezial_Results_Discretionary(1,:)  = [];

All_Spezial_TotalAktiva(1,:)        = [];
All_Spezial_TotalCash(1,:)          = [];
All_Spezial_TotalFondsverm(1,:)     = [];
All_Spezial_TotalHoldings(1,:)      = [];
All_Spezial_TotalHoldings_Lag(1,:)  = [];
All_Spezial_TotalLeverage(1,:)      = [];
All_Spezial_TotalPassiva(1,:)       = [];
All_Spezial_TotalFlows(1,:)         = [];

% Save dataset
save(strcat(projectPath, 'Data\Empirical_PartI_CovidTrading'));
